package com.partvoyage.server.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.servlet.http.HttpSession;

import com.google.appengine.api.users.User;
import com.partvoyage.shared.Constants;
import com.partvoyage.shared.model.AccessToken;

public class ServletUtils {
	public static String getAccessTokenScopeKey(String scope) {
		return Constants.SESSION_OAUTH_ACCESS_TOKEN + "_" + scope;
	}

	public static AccessToken getAccessTokenFromSession(String scope,
			HttpSession session) {
		return (AccessToken) session
				.getAttribute(getAccessTokenScopeKey(scope));
	}

	public static void setAccessTokenToSession(String scope,
			AccessToken accessToken, HttpSession session) {
		session.setAttribute(getAccessTokenScopeKey(scope), accessToken);
	}

	public static void removeAccessTokenFromSession(String scope,
			HttpSession session) {
		session.removeAttribute(getAccessTokenScopeKey(scope));
	}

	public static String toString(InputStream stream) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(stream));
		String line;

		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
		} catch (Exception e) {
			// NOP
		}

		return sb.toString();
	}

	public static User getCurrentUserFromSession(HttpSession session) {
		return (User) session.getAttribute(Constants.SESSION_USER);

	}

	public static void setCurrentUserToSession(User currentUser,
			HttpSession session) {
		session.setAttribute(Constants.SESSION_USER, currentUser);

	}
}
